package com.ruitu.mall_98_2.mine;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.beanu.arad.Arad;
import com.beanu.arad.base.my_base.MyBaseActivity;
import com.beanu.arad.utils.MD5Util;
import com.beanu.arad.utils.RegexUtils;
import com.beanu.arad.utils.ToastUtils;
import com.beanu.arad.view.IdentifyingCode;
import com.beanu.arad.widget.progressactivity.ProgressLayout;
import com.bumptech.glide.Glide;
import com.ruitu.mall_98_2.R;
import com.ruitu.mall_98_2.dao.APIRetrofit;
import com.ruitu.mall_98_2.mvp.contract.RelevanceTelContract;
import com.ruitu.mall_98_2.mvp.model.RelevanceTelModel;
import com.ruitu.mall_98_2.mvp.presenter.RelevanceTelPresenter;
import com.ruitu.router_module.AppHolder;
import com.ruitu.router_module.bean.EventModel;
import com.ruitu.router_module.bean.User;
import com.ruitu.router_module.bean.api.BaseResult;
import com.ruitu.router_module.bean.api.SubscriberImpl;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class RelevanceTelActivity extends MyBaseActivity<RelevanceTelPresenter, RelevanceTelModel> implements RelevanceTelContract.View {
    private String name;
    private String imageUrl;
    private ImageView iv_qq_head;
    private TextView tv_qq_nike, tv_three_login, tv_get_code, et_iv_verifactiion_code;
    private EditText et_tel, et_get_code, et_password;
    private CheckBox ck_password_select;//密码可见选择器
    private ImageView iv_verifactiion_code;
    private String account;
    private String password;
    private String unionid;
    private String type;
    private int delayTime = 60;
    private boolean isTimeGoOn = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHeadTitle("第三方账号绑定");
        name = getIntent().getStringExtra("name");
        imageUrl = getIntent().getStringExtra("imageUrl");
        unionid = getIntent().getStringExtra("unionid");
        type = getIntent().getStringExtra("type");
        if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(imageUrl)) {
            tv_qq_nike.setText(name);
            Glide.with(this).load(imageUrl)
                    .into(iv_qq_head);
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (tv_three_login == v) {
            account = et_tel.getText().toString();
            password = et_password.getText().toString();
            String code = et_get_code.getText().toString();
            if (TextUtils.isEmpty(account)) {
                ToastUtils.showShort("手机号不能为空");
                return;
            }
            if (RegexUtils.isPassword(password)) {
                showProgress();
                mPresenter.registerForQqOrWx(unionid, type, account, MD5Util.md5String(password), code, name);
            } else {
                ToastUtils.showShort("请输入正确格式的密码");
            }

        }

        if (tv_get_code == v) {
            account = et_tel.getText().toString();
            if (!TextUtils.isEmpty(account)) {
                if (TextUtils.equals(et_iv_verifactiion_code.getText().toString().toLowerCase(), resultCode)) {
                    tv_get_code.setEnabled(false);
                    setGetCodeTime(60);
                    isTimeGoOn = true;
                    handler.sendEmptyMessageDelayed(979, 1000);
                    getCode();
                } else {
                    ToastUtils.showShort("图片验证不正确");
                }
            } else {
                ToastUtils.showShort("手机号不能为空");
            }
            getVerifactionCode();
        }

        if (iv_verifactiion_code == v) {
            getVerifactionCode();
        }
    }

    String resultCode;

    private void getVerifactionCode() {
        iv_verifactiion_code.setImageBitmap(IdentifyingCode.getInstance().createBitmap());
        resultCode = IdentifyingCode.getInstance().getCode().toLowerCase();
    }


    @Override
    protected int getLayoutRes() {
        return R.layout.activity_relevance_tel;
    }

    @Override
    protected ProgressLayout findProgressLayout() {
        return null;
    }

    @Override
    protected void initViews() {
        super.initViews();
        iv_qq_head = findViewById(R.id.iv_qq_head);
        tv_qq_nike = findViewById(R.id.tv_qq_nike);
        tv_three_login = findViewById(R.id.tv_three_login);
        tv_get_code = findViewById(R.id.tv_get_code);
        et_tel = findViewById(R.id.et_tel);
        et_get_code = findViewById(R.id.et_get_code);
        et_password = findViewById(R.id.et_password);
        ck_password_select = findViewById(R.id.ck_password_select);
        et_iv_verifactiion_code = findViewById(R.id.et_iv_verifactiion_code);
        iv_verifactiion_code = findViewById(R.id.iv_verifactiion_code);
        setListener();
        getVerifactionCode();
    }

    private void setListener() {
        tv_get_code.setOnClickListener(this);
        tv_three_login.setOnClickListener(this);
        iv_verifactiion_code.setOnClickListener(this);

        ck_password_select.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    et_password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    et_password.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
            }
        });
    }

    @Override
    public void registerAccounts(User user) {
        Arad.preferences.putString("tel", account).flush();
        Arad.preferences.putString("psw", password).flush();
        AppHolder.instance().setUser(user);
        Arad.bus.post(new EventModel<String>(18113000));
        Arad.bus.post(new EventModel(18110900));
        finish();
    }

    public void getCode() {
        APIRetrofit.getDefault().smsSend(account, "1")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SubscriberImpl<BaseResult>() {
                    @Override
                    public void onError(Throwable e) {
                        hideProgress();
                        ToastUtils.showShort("获取验证码失败,请重试");
                    }

                    @Override
                    public void onNext(BaseResult stringBaseResult) {
                        hideProgress();
                        if (stringBaseResult.isSuccess()) {
                            ToastUtils.showShort(stringBaseResult.getMsg());
                        } else {
                            ToastUtils.showShort(stringBaseResult.getMsg());
                        }
                    }
                });
    }

    private void setGetCodeTime(int timer) {
        if (timer == 0) {
            tv_get_code.setEnabled(true);
            isTimeGoOn = false;
            tv_get_code.setText("获取验证码");
            delayTime = 60;
        } else {
            tv_get_code.setText(timer + "s后重新获取");
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 979) {
                if (isTimeGoOn) {
                    setGetCodeTime(--delayTime);
                    handler.sendEmptyMessageDelayed(979, 1000);
                }
            }
        }
    };
}
